export default {
	namespaced: true,
	state: () => ({

		// {goods_id name price count small_logo goods_state}
		cart: JSON.parse(uni.getStorageSync('cart') || '[]') // 假设购物车状态
	}),
	mutations: {
		//加入购物车

		addToCart(state, goods) {
			// 先判断商品是否存在购物车中，存在则直接加count加1
			//不存在在加入到购物车中

			const findResult = state.cart.find(x => x.goods_id === goods.goods_id)


			if (!findResult) {
				// 没有加入购物车
				state.cart.push(goods)
			} else {
				//有数量加1
				findResult.goods_count++
			}
			this.commit('my_cart/saveToStorage')
		},
		//持久化存储
		saveToStorage(state) {
			uni.setStorageSync('cart', JSON.stringify(state.cart))
		},
		//点击后修改状态
		updateGoodsState(state, goods) {
			const findResult = state.cart.find(x => x.goods_id === goods.goods_id)


			if (findResult) {
				// 修改状态
				findResult.goods_state = goods.goods_state

			}
			this.commit('my_cart/saveToStorage')

		},
		//点击后修改数量
		updateGoodsCount(state, goods) {
			const findResult = state.cart.find(x => x.goods_id === goods.goods_id)
			if (findResult) {
				// 修改状态
				findResult.goods_count = goods.goods_count

			}
			this.commit('my_cart/saveToStorage')

		},
		//根据id删除对应商品信息
		removeById(state, goods_id) {
			state.cart = state.cart.filter(x => x.goods_id !== goods_id)

			this.commit('my_cart/saveToStorage')

		},
		// 更新所有商品的状态 全选 反选  newstate 为全选按钮的状态
		updateAllGoodsState(state, newState) {
			//根据 全选按钮的状态去给按钮赋值
			state.cart.forEach(e => e.goods_state = newState)
			this.commit('my_cart/saveToStorage')
		},

	},
	getters: {
		checkCount(state) {
			//计算已勾选的商品的总数量 total为返回值 
			return state.cart.filter(x => x.goods_state).reduce((total, item) => total += item.goods_count, 0)
		},
		//统计商品总数量
		total(state) {
			let c = 0
			state.cart.forEach(goods => c += goods.goods_count)
			return c
		},
		//统计价格
		countTotalMoney(state) {
			return state.cart.reduce((total, item) => total += item.goods_price * item.goods_count, 0).toFixed(2)
		}
	}

}